/*
 * Created on Wed Jun 06 2018 by Ronnie Ren (zhaosong.ren) from Accenture
 *
 * Copyright (c) 2018 DingXing information & technology limited company.
 */

import { Injectable } from "@angular/core";
import {JsonMappingUtil} from "../../json-mapping-util";
import {InspectionRecords} from '../../transform/inspection/inspection-records';
import {InspectionRecordsDto} from '../../dto/inspection/inspection-records.dto';
import { CurdService } from "../curd.service";
import { Observable } from "rxjs";
import { SyncUtilService } from "../../../services/offline/sync.util.service";
import {SyncStatus} from "../../sync-status";
import { AttachmentService } from "../attachment.service";


@Injectable()
export class InspectionRecordsService {

    constructor(
        private curdService: CurdService,
        private syncUtilService: SyncUtilService,
        private attachmentService: AttachmentService
    ) {

    }

    fetchInspectionRecordsBySyncStatus(syncStatuses: Array<SyncStatus>, count: number = 1): Observable<Array<InspectionRecords>> {
      return this.curdService.observableFetchObjectsByPage(
        InspectionRecordsDto,
        null,
        [{ syncStatus: syncStatuses }]
      )
        .flatMap((inspectionRecordsDtos: Array<InspectionRecordsDto>) => {
          if (!inspectionRecordsDtos || inspectionRecordsDtos.length < 1 ) {
            return Observable.of([]);
          } else {
            return Observable.combineLatest(
              inspectionRecordsDtos.map((inspectionRecordsDto) =>
                this.getInspectionRecordsAndAttachmentsFromInspectionRecordsDtos(inspectionRecordsDto))
            )
              .map((billsArray) => billsArray.reduce((result, bills) => result.concat(bills), []));
          }
        });
    }

    getInspectionRecordsAndAttachmentsFromInspectionRecordsDtos(inspectionRecordsDto: InspectionRecordsDto): Observable<InspectionRecords> {
      let inspectionRecord = new InspectionRecords({});
      JsonMappingUtil.MappingAllProp(inspectionRecordsDto, inspectionRecord);
      if (!inspectionRecord.pictureAttachmentIds) {
        inspectionRecord.pictureAttachmentIds = '';
      }
      return this.attachmentService.fetchAttachmentByIds(inspectionRecord.pictureAttachmentIds.split(","))
        .do((attachments) => {
          console.log(attachments, "attachments ------");
          inspectionRecord.pictureAttachments = attachments;
          console.log(inspectionRecord, "inspectionRecord ------");
        })
        .map(() => {
          console.log(inspectionRecord);
          return inspectionRecord;
        });
    }

    getRecords(plannedId: string): Observable<InspectionRecords> {
        return this.curdService.observableFetchObjects(InspectionRecordsDto, {taskId: plannedId})
        .map((objs: Array<{}>) => {
            if (objs && objs.length > 0) {
                let dto = new InspectionRecordsDto();
                return JsonMappingUtil.MappingAllProp(objs[0], dto);
            }
            return null;
        })
        .map((dto) => {
            if (dto) {
                let model = new InspectionRecords({});
                return JsonMappingUtil.MappingAllProp(dto, model);
            }
            return null;
        });
    }

    addRecords(data) {

        return this.curdService.addRows([this.syncUtilService.toObjectDto(data, InspectionRecordsDto)]);
    }

    updateRecords(data) {
        // console.log("gengxinshuju" + JSON.stringify(data));
        return this.curdService.updateRow(
            this.syncUtilService.toObjectDto(data, InspectionRecordsDto),
            {taskId:  data.taskId});

        // return Observable.fromPromise(
        //     this.curdService.update({dto: InspectionRecordsDto, mapObj: InspectionRecords}, data, data.taskId)
        // );
    }

}
